package com.demo.hc.common.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * http请求工具类
 */
public class HttpUtil {

    /**
     * POST提交
     */
    public static Map<String, Object> post(String url, String body) throws ClientProtocolException, IOException {
        CloseableHttpClient client = createSSLInsecureClient();
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(25000).setConnectTimeout(25000).setSocketTimeout(25000).build();
        HttpPost request = new HttpPost(url);
        request.setConfig(requestConfig);
        request.addHeader("Content-Type", "text/xml; charset=UTF-8");
        if (!StringUtils.isEmpty(body)) {
            EntityBuilder builder = EntityBuilder.create();
            builder.setContentEncoding("utf-8");
            builder.setContentType(ContentType.create("text/xml", Charset.forName("utf-8")));
            builder.setText(body);
            HttpEntity entity = builder.build();
            request.setEntity(entity);
        }
        CloseableHttpResponse response = client.execute(request);
        try {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                String result = EntityUtils.toString(resEntity, Charset.forName("utf-8"));
                EntityUtils.consume(resEntity);
                Map<String, Object> map = null;
                if (StringUtils.isNotEmpty(result)) {
                    map = JsonUtil.toMap(result);
                }
                return map;
            }
        } finally {
            request.releaseConnection();
            response.close();
            client.close();
        }
        return null;
    }

    /**
     * GET
     */
    public static Map<String, Object> get(String url) throws IOException {
        CloseableHttpClient client = createSSLInsecureClient();
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(25000).setConnectTimeout(25000).setSocketTimeout(25000).build();
        HttpGet request = new HttpGet(url);
        request.setConfig(requestConfig);
        request.addHeader("Content-Type", "text/xml; charset=UTF-8");
        CloseableHttpResponse response = client.execute(request);
        try {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                String result = EntityUtils.toString(resEntity, Charset.forName("utf-8"));
                EntityUtils.consume(resEntity);
                return JsonUtil.toMap(result);
            }
        } finally {
            request.releaseConnection();
            response.close();
            client.close();
        }
        return null;
    }

    /**
     * 信任自签及所有证书
     */
    public static CloseableHttpClient createSSLInsecureClient() {
        try {
            SSLContextBuilder builder = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }

    /**
     * GET
     */
    public static String getByObject(String url) throws ClientProtocolException, IOException {
        CloseableHttpClient client = createSSLInsecureClient();
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(25000).setConnectTimeout(25000).setSocketTimeout(25000).build();
        HttpGet request = new HttpGet(url);
        request.setConfig(requestConfig);
        request.addHeader("Content-Type", "text/xml; charset=UTF-8");
        CloseableHttpResponse response = client.execute(request);
        try {
            if (response == null || response.getStatusLine() == null || response.getStatusLine().getStatusCode() != 200)
                return null;
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                String result = EntityUtils.toString(resEntity, Charset.forName("utf-8"));
                EntityUtils.consume(resEntity);
                return result;
            }
        } finally {
            request.releaseConnection();
            response.close();
            client.close();
        }
        return null;
    }

}
